<link rel="stylesheet" href="${request.contextPath}/assets/bower_components/jquery-ztree/zTreeStyle.css">
<link rel="stylesheet" href="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/css/bootstrapValidator.css"/>
<script type="text/javascript" src="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/js/bootstrapValidator.js"></script>
<script type="text/javascript" src="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/js/language/zh_CN.js"></script>
<section class="content-header">
	<h1>&nbsp;</h1>
	<ol class="breadcrumb">
		<li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
		<li class="active"><a>公司管理</a></li>
	</ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
	<div class="row">
		<div class="col-xs-12">
			<div class="box">
				<div class="box-body">
					<!-- 搜索条件 -->
					<table class="table">
						<tr height="45px" bgcolor="#F3F3F3">
						    <td align="left" style="width:250px;">
								<form action="#" method="get" class="">
							        <div class="input-group">
							          <input type="text" name="q" class="form-control" placeholder="Search...">
							              <span class="input-group-btn">
							                <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
							                </button>
							              </span>
							        </div>
							      </form>
							</td>
							<td align="left">
								<button	class="btn btn-danger btn-small" data-toggle="modal" onclick="showadddialog();">添加</button>
							</td>
						</tr>
					</table>
					<!-- 结果列表 -->
					<table id="myTableData"
						class="table table-bordered table-condensed table-hover table-striped">
						<thead>
							<tr>
								<th>ID</th>
								<th>序号</th>
								<th>公司名称</th>
								<th>所属行业</th>
								<th>联系人</th>
								<th>联系电话</th>
								<th>上级公司</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</section>

<div class="modal fade" id="modal-default">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="orgdialogtitle">添加公司</h4>
      </div>
      <div class="modal-body">
        
        <form class="form-horizontal" id="defaultForm">
              <div class="box-body">
                <div class="form-group">
                  <label class="col-sm-2 control-label">上级公司</label>
                  <div class="col-sm-9">
                    	<input class='link-url form-control' id='pid' type='text'
								onclick="showMenu();" placeholder='选择公司' readonly="true"/>
						<input type="hidden" id="parentid" />
						<div id="menuContent" class="menuContent"
							style="display:none;position: absolute;z-index:999">
							<ul id="treeDemo" class="ztree"
								style="margin-top:0; width:130%;min-height: 215px;"></ul>
						</div>
                  </div>
                </div>
                <div class="form-group" id="errorcom">
                  <label class="col-sm-2"></label>
                  <div class="col-sm-9 promptAddMsg">目前公司存在子公司，无法修改</div>
                </div>
                <div class="form-group">
                  <label for="name" class="col-sm-2 control-label">公司名称</label>
                  <div class="col-sm-9">
                    <input type="hidden" class="form-control" id="orgid">
                    <input type="text" class="form-control" id="name" name="name" placeholder="公司名称">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id">*</span>
                  </div>
                </div>
                <div class="form-group">
                  <label for="legal" class="col-sm-2 control-label">法人</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="legal" placeholder="法人">
                  </div>
                </div>
                <div class="form-group">
                  <label for="linkman" class="col-sm-2 control-label">联系人</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="linkman" placeholder="联系人">
                  </div>
                </div>
				<div class="form-group">
                  <label for="linkphone" class="col-sm-2 control-label">手机号码</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="linkphone" name="linkphone" placeholder="手机号码">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id">*</span>
                  </div>
                </div>                
                <div class="form-group">
                  <label for="industrytype" class="col-sm-2 control-label">所属行业</label>
                  <div class="col-sm-9">
                  	<select id="industrytype" name="industrytype" class="form-control"></select>
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id">*</span>
                  </div>
                </div>
                <div class="form-group">
                  <label for="introduction" class="col-sm-2 control-label">公司简介</label>
                  <div class="col-sm-9">
                  	<textarea class="form-control" id="introduction" placeholder="公司简介"></textarea>
                  </div>
                </div>
                
                <div class="box-footer">
              	<div class="pull-right">
	              	<button type="button" id="saveorg" class="btn btn-info">确定</button>
	                &nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
              	</div>
              </div>
              </div>
            </form>
            
      </div>
      <!-- <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" onclick="saveorg();">保存</button>
      </div> -->
    </div>
  </div>
</div>

	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.core-3.5.min.js"></script>
	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.exedit-3.5.min.js"></script>
		
<script>
   
   $(function(){
	 $("#myTableData").dataTable({
		 lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
         paging: true,//分页
         ordering: true,//是否启用排序
         searching: false,//搜索
         language: {
       	  lengthMenu: '',//左上角的分页大小显示。
             paginate: {//分页的样式内容。
                 previous: "上一页",
                 next: "下一页",
                 first: "首页",
                 last: "末页"
             },
             zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
             //下面三者构成了总体的左下角的内容。
             info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
             infoEmpty: "0条记录",//筛选为空时左下角的显示。
             infoFiltered: ""//筛选之后的左下角筛选提示，
         },
         pagingType: "full_numbers",//分页样式的类型
         "serverSide": true,
          ajax: function (data, callback, settings) {
              //封装请求参数
              var param = {};
              param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
              param.start = data.start;//开始的记录序号
              param.page = (data.start / data.length)+1;//当前页码
              param.orderby=data.orderBys;
              //ajax请求数据
              $.ajax({
                  type: "post",
                  url: "${request.contextPath}/user/getOrgList",
                  cache: false,  //禁用缓存
                  data: param,  //传入组装的参数
                  dataType: "json",
                  success: function (result) {
                      //封装返回数据
                      var returnData = {};
                      returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                      returnData.recordsTotal = result.total;//返回数据全部记录
                      returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                      returnData.data = result.pageData;//返回的数据列表
                      //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                      //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                      callback(returnData);
                  }
              });
          },
          //列表表头字段
          columns: [
              { "data": "id" },
              { "data": null},
              { "data": "name" },
              { "data": "industrytypevalue" },
              { "data": "linkman" },
              { "data": "linkphone" },
              { "data": "pname" },
              { "data": null}
          ],
         fnDrawCallback  : function(){
             this.api().column(1).nodes().each(function(cell, i) {
                 cell.innerHTML =  i + 1;
             });
         },
          "aoColumnDefs":[
              {
                  "targets":0,
                  "visible":false
              },
              {//倒数第一列
                  "targets":-1,
                  "bSortable": false,
                  render: function(data, type, row) {
                      var html ='<button class="btn btn-success btn-small" onclick="showeditdialog(\''+data.id+'\',\''+data.name+'\');">编辑</button>'
                      /* +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="deluser(\''+data.id+'\');">修改权限</button>'
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="deluser(\''+data.id+'\');">分配车辆</button>' */
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-danger btn-small" onclick="delorg(\''+data.id+'\');">删除</button>';
                      return html;
                  }
              },
           ]
      });
      
	 $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
	 
	 var data = {type:'industry_type'};
	 $.ajax({
			url : "${request.contextPath}/user/getDic",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					var industrytypeArr = s.other;
					$("#industrytype").empty();
        			for(var i=0;i<industrytypeArr.length;i++){
        				$("#industrytype").append("<option value='"+industrytypeArr[i].key+"'>"+industrytypeArr[i].value+"</option>");
        			}
				}
			}
		});
	 
	 
	 $('#defaultForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {	        	
	            name: {
	                validators: {
	                    notEmpty: {
	                        message: '公司名称不能为空'
	                    }
	                }
	            },
	            industrytype: {
	                validators: {
	                    notEmpty: {
	                        message: '所属行业不能为空'
	                    }
	                }
	            },
	            linkphone: {
	                validators: {
	                	notEmpty: {
	                        message: '手机号码不能为空'
	                    },
	                	stringLength: {
	                         min: 11,
	                         max: 11,
	                         message: '请输入11位手机号码'
	                     },
	                     regexp: {
	                         regexp: /^1[3|5|7|8]{1}[0-9]{9}$/,
	                         message: '请输入正确的手机号码'
	                     }
	                }
	            },
	        }
	    });
	   
	   $("#saveorg").on("click", function(){
		     //获取表单对象
		    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
	        //手动触发验证
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	            //表单提交的方法、比如ajax提交
	            saveorg();
	        }
		});
	 
   }); 
   
   function onClick(e, treeId, treeNode) {
  		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
  		nodes = zTree.getSelectedNodes(),
  		v = "";
  		pv = "";
  		nodes.sort(function compare(a,b){return a.id-b.id;});
  		for (var i=0, l=nodes.length; i<l; i++) {
  			v += nodes[i].name + ",";
  			pv += nodes[i].id + ",";
  		}
  		if (v.length > 0 ) v = v.substring(0, v.length-1);
  		var cityObj = $("#pid");
  		cityObj.attr("value", v);
  		
  		if (pv.length > 0 ) pv = pv.substring(0, pv.length-1);
  		var cityObj2 = $("#parentid");
  		cityObj2.attr("value", pv);
  		
  		hideMenu();
  	}

  	function showMenu() {
  		var cityObj = $("#pid");
  		var cityOffset = $("#pid").offset();
  		$("#menuContent").slideDown("fast");
  		$("body").bind("mousedown", onBodyDown);
  	}
  	function hideMenu() {
  		$("#menuContent").fadeOut("fast");
  		$("body").unbind("mousedown", onBodyDown);
  	}
  	function onBodyDown(event) {
  		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
  			hideMenu();
  		}
  	}
  	
   function showadddialog()
   {
	   $("#orgid").val("-1");
	   $("#name").val("");
	   $("#legal").val("");
	   $("#linkman").val("");
	   $("#linkphone").val("");
	   $("#industrytype").val("");
	   $("#introduction").val("");
	   
	   $("#pid").removeAttr("disabled");
	   $("#errorcom").hide();
	   
	   $("#orgdialogtitle").text("添加公司");
	   
	   $("#modal-default").modal('show');
   }
   
   function showeditdialog(id,name)
   {
	   $("#orgid").val(id);
	   
	   var data = {id:id}
	   $.ajax({
			url : "${request.contextPath}/user/getOrg",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					
				    var org = s.other;
				    
				    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				    var snode = zTree.getNodeByParam("id",org.pid, null);
				    if (snode)
			    	{
				    	$("#pid").attr("value",snode.name);
					    zTree.selectNode(snode);
					    $("#parentid").attr("value", org.pid);
			    	}
				    else
			    	{
				    	$("#pid").attr("value",'选择公司');
				    	$("#parentid").attr("value", 0);
			    	}
				    if (org.childs == 0)
			    	{
				    	$("#errorcom").hide();
				    	$("#pid").removeAttr("disabled");
			    	}
				    else
			    	{
				    	$("#errorcom").show();
				    	$("#pid").attr("disabled","disabled");
			    	}
					$("#name").val(org.name);
				    $("#legal").val(org.legal);
				    $("#linkman").val(org.linkman);
				    $("#linkphone").val(org.linkphone);
				    $("#industrytype").val(org.industrytype);
				    $("#introduction").val(org.introduction);
					   
				    $("#orgdialogtitle").text("编辑公司");
				    
					$("#modal-default").modal('show');
				} else {
					alert(s.msg);
				}
			}
		}); 
	   
	   
   }
   
   function delorg(id)
   {
	   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
		   var data = {id:id}
		   $.ajax({
				url : "${request.contextPath}/user/delOrg",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			}); 
	   });
   }
   
   function saveorg()
   {
	   var orgid = $("#orgid").val();
	   orgid = parseInt(orgid);
	   //var role = $("#role").val();
	   var pid = $("#parentid").val();
	   if (pid == '')
	   {
		   pid = 0;
	   }
	   else
	   {
		   pid = parseInt(pid);
	   }
	   var name = $("#name").val();
	   var legal = $("#legal").val();
	   var linkman = $("#linkman").val();
	   var linkphone = $("#linkphone").val();
	   var industrytype = $("#industrytype").val();
	   var introduction = $("#introduction").val();
	      
	   if (orgid == -1)
	   {
		   var data = {
			   pid:pid,
			   name:name,
			   legal:legal,
			   linkman:linkman,
			   linkphone:linkphone,
			   industrytype:industrytype,
			   introduction:introduction
		   }
		   $.ajax({
				url : "${request.contextPath}/user/saveOrg",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
	   else
	   {
		   var data = {
				   id:orgid,
				   pid:pid,
				   name:name,
				   legal:legal,
				   linkman:linkman,
				   linkphone:linkphone,
				   industrytype:industrytype,
				   introduction:introduction
			   }
		   $.ajax({
				url : "${request.contextPath}/user/updateOrg",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
   }
 </script>